#!/usr/bin/env bash
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/openresty-vhosts/internal-functions"
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x

cmd-openresty-report() {
  declare desc="displays a openresty report for one or more apps"
  declare cmd="openresty:report"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1" INFO_FLAG="$2"

  if [[ -n "$APP" ]] && [[ "$APP" == --* ]]; then
    INFO_FLAG="$APP"
    APP=""
  fi

  if [[ -z "$APP" ]] && [[ -z "$INFO_FLAG" ]]; then
    INFO_FLAG="true"
  fi

  if [[ -z "$APP" ]]; then
    for app in $(dokku_apps); do
      cmd-openresty-report-single "$app" "$INFO_FLAG" | tee || true
    done
  else
    cmd-openresty-report-single "$APP" "$INFO_FLAG"
  fi
}

cmd-openresty-report-single() {
  declare APP="$1" INFO_FLAG="$2"
  if [[ "$INFO_FLAG" == "true" ]]; then
    INFO_FLAG=""
  fi
  verify_app_name "$APP"
  local flag_map=(
    "--openresty-access-log-format: $(fn-openresty-access-log-format "$APP")"
    "--openresty-access-log-path: $(fn-openresty-access-log-path "$APP")"
    "--openresty-allowed-letsencrypt-domains-func-base64: $(fn-openresty-allowed-letsencrypt-domains-func-base64)"
    "--openresty-bind-address-ipv4: $(fn-openresty-bind-address-ipv4 "$APP")"
    "--openresty-bind-address-ipv6: $(fn-openresty-bind-address-ipv6 "$APP")"
    "--openresty-client-body-timeout: $(fn-openresty-client-body-timeout "$APP")"
    "--openresty-client-header-timeout: $(fn-openresty-client-header-timeout "$APP")"
    "--openresty-client-max-body-size: $(fn-openresty-client-max-body-size "$APP")"
    "--openresty-error-log-path: $(fn-openresty-error-log-path "$APP")"
    "--openresty-global-hsts: $(fn-plugin-property-get-default "openresty" "--global" "hsts" "true")"
    "--openresty-computed-hsts: $(fn-openresty-hsts-is-enabled "$APP")"
    "--openresty-hsts: $(fn-plugin-property-get-default "openresty" "$APP" "hsts" "")"
    "--openresty-hsts-include-subdomains: $(fn-openresty-hsts-include-subdomains "$APP")"
    "--openresty-hsts-max-age: $(fn-openresty-hsts-max-age "$APP")"
    "--openresty-hsts-preload: $(fn-openresty-hsts-preload "$APP")"
    "--openresty-image: $(fn-openresty-image)"
    "--openresty-keepalive-timeout: $(fn-openresty-keepalive-timeout "$APP")"
    "--openresty-letsencrypt-email: $(fn-openresty-letsencrypt-email)"
    "--openresty-letsencrypt-server: $(fn-openresty-letsencrypt-server)"
    "--openresty-lingering-timeout: $(fn-openresty-lingering-timeout "$APP")"
    "--openresty-proxy-buffer-size: $(fn-openresty-proxy-buffer-size "$APP")"
    "--openresty-proxy-buffering: $(fn-openresty-proxy-buffering "$APP")"
    "--openresty-proxy-buffers: $(fn-openresty-proxy-buffers "$APP")"
    "--openresty-proxy-busy-buffers-size: $(fn-openresty-proxy-busy-buffers-size "$APP")"
    "--openresty-proxy-connect-timeout: $(fn-openresty-proxy-connect-timeout "$APP")"
    "--openresty-proxy-read-timeout: $(fn-openresty-proxy-read-timeout "$APP")"
    "--openresty-proxy-send-timeout: $(fn-openresty-proxy-send-timeout "$APP")"
    "--openresty-send-timeout: $(fn-openresty-send-timeout "$APP")"
    "--openresty-underscore-in-headers: $(fn-openresty-underscore-in-headers "$APP")"
    "--openresty-x-forwarded-for-value: $(fn-openresty-x-forwarded-for-value "$APP")"
    "--openresty-x-forwarded-port-value: $(fn-openresty-x-forwarded-port-value "$APP")"
    "--openresty-x-forwarded-proto-value: $(fn-openresty-x-forwarded-proto-value "$APP")"
    "--openresty-x-forwarded-ssl: $(fn-openresty-x-forwarded-ssl "$APP")"
  )

  if [[ -z "$INFO_FLAG" ]]; then
    dokku_log_info2_quiet "${APP} openresty information"
    for flag in "${flag_map[@]}"; do
      key="$(echo "${flag#--}" | cut -f1 -d' ' | tr - ' ')"
      dokku_log_verbose "$(printf "%-30s %-25s" "${key^}" "${flag#*: }")"
    done
  else
    local match=false
    local value_exists=false
    for flag in "${flag_map[@]}"; do
      valid_flags="${valid_flags} $(echo "$flag" | cut -d':' -f1)"
      if [[ "$flag" == "${INFO_FLAG}:"* ]]; then
        value=${flag#*: }
        size="${#value}"
        if [[ "$size" -ne 0 ]]; then
          echo "$value" && match=true && value_exists=true
        else
          match=true
        fi
      fi
    done
    [[ "$match" == "true" ]] || dokku_log_fail "Invalid flag passed, valid flags:${valid_flags}"
  fi
}

cmd-openresty-logs() {
  declare desc="display openresty logs from command line"
  declare cmd="openresty:logs"
  [[ "$1" == "$cmd" ]] && shift 1
  local NUM="100" TAIL=false

  local TEMP=$(getopt -o htn: --long help,tail,num: -n 'dokku openresty:logs' -- "$@")
  local EXIT_CODE="$?"
  if [[ "$EXIT_CODE" != 0 ]]; then
    fn-openresty-logs-usage >&2
    exit 1
  fi
  eval set -- "$TEMP"

  while true; do
    case "$1" in
      -t | --tail)
        local TAIL=true
        shift
        ;;
      -n | --num)
        local NUM="$2"
        shift 2
        ;;
      --)
        shift
        break
        ;;
      *) dokku_log_fail "Internal error" ;;
    esac
  done

  fn-openresty-logs "$TAIL" "$NUM"
}

cmd-openresty-show-config() {
  declare desc="display openresty config"
  declare cmd="openresty:show-config"
  [[ "$1" == "$cmd" ]] && shift 1

  if ! fn-is-compose-installed; then
    dokku_log_fail "Required docker compose plugin is not installed"
  fi

  local TMP_COMPOSE_FILE=$(mktemp "/tmp/dokku-${DOKKU_PID}-${FUNCNAME[0]}.XXXXXX")
  trap "rm -rf '$TMP_COMPOSE_FILE' >/dev/null" RETURN INT TERM EXIT

  fn-openresty-template-compose-file "$TMP_COMPOSE_FILE"
  cat "$TMP_COMPOSE_FILE"
}

cmd-openresty-start() {
  declare desc="Starts the openresty server"
  declare cmd="openresty:start"
  [[ "$1" == "$cmd" ]] && shift 1

  if ! fn-is-compose-installed; then
    dokku_log_fail "Required docker compose plugin is not installed"
  fi

  local TMP_COMPOSE_FILE=$(mktemp "/tmp/dokku-${DOKKU_PID}-${FUNCNAME[0]}.XXXXXX")
  trap "rm -rf '$TMP_COMPOSE_FILE' >/dev/null" RETURN INT TERM EXIT

  fn-plugin-property-write "openresty" "--global" "proxy-status" "started"
  fn-openresty-template-compose-file "$TMP_COMPOSE_FILE"
  "$DOCKER_BIN" compose -f "$TMP_COMPOSE_FILE" -p openresty up -d --quiet-pull
}

cmd-openresty-stop() {
  declare desc="Starts the openresty server"
  declare cmd="openresty:stop"
  [[ "$1" == "$cmd" ]] && shift 1

  if ! fn-is-compose-installed; then
    dokku_log_fail "Required docker compose plugin is not installed"
  fi

  local TMP_COMPOSE_FILE=$(mktemp "/tmp/dokku-${DOKKU_PID}-${FUNCNAME[0]}.XXXXXX")
  trap "rm -rf '$TMP_COMPOSE_FILE' >/dev/null" RETURN INT TERM EXIT

  fn-plugin-property-write "openresty" "--global" "proxy-status" "stopped"
  fn-openresty-template-compose-file "$TMP_COMPOSE_FILE"
  "$DOCKER_BIN" compose -f "$TMP_COMPOSE_FILE" -p openresty down --remove-orphans
}
